package com.sywl.web.util;

import java.util.ArrayList;
import java.util.List;

/**
 * 简单的分页实现
 * @author itachi
 *
 */
public class SinglePage implements Page {

	private List<Integer> pages;

	private int page;

	private int count;

	private int prev;

	private int next;

	private int first;

	private int last;

	private int maxResult;

	@Override
	public List<Integer> getPages() {
		return pages;
	}

	@Override
	public int getPage() {
		return page >= 1 && page <= last ? page : 1;
	}

	@Override
	public int getCount() {
		return count;
	}

	@Override
	public int getPrev() {
		return prev;
	}

	@Override
	public int getNext() {
		return next;
	}

	@Override
	public int getFirst() {
		return first;
	}

	@Override
	public int getLast() {
		return last;
	}

	@Override
	public int getPageSize() {
		return last;
	}
	
	@Override
	public boolean isValid() {
		return page >= 1 && page <= last;
	}
	
	@Override
	public int getMaxResult() {
		return maxResult;
	}
	
	public SinglePage(int count, int page, int maxResult, boolean useDefaultPages) {
		this.count = count;
		this.page = page;
		this.maxResult = maxResult;
		calePage();
		if(useDefaultPages) {
			calePages(3, 7);
		}
	}

	private void calePage() {
		last = count % maxResult == 0 ? count / maxResult : count / maxResult
				+ 1;
		last = last < 1 ? 1 : last;
		prev = page > 1 && page <= last ? page - 1 : 1;
		next = page > 0 && page < last ? page + 1 : 1;
		first = (page - 1) * maxResult;
	}

	public Page calePages(int position, int length) {
		pages = new ArrayList<Integer>();
		int start = page - position;
		start = start < 1 || position > last? 1 : start;
		for (int i = start; i < start + length; i++) {
			if (i > 0 && i <= last) {
				pages.add(i);
			}
		}
		return this;
	}

}
